<?php

class Admin_CompanyController extends Zend_Controller_Action
{
    public function indexAction()
    {
        echo Application_Model_CommonTools::transliterate('Яма йой їоїоїой');
    }

    /**
     * Read the $_POST, creates and returns Company object
     *
     * @return Application_Model_Company
     */
    protected function _postToCompanyObj() {
        $company = new Application_Model_Company();
        $c = $company;
        $errors = array();

        $c->setAdresa($_POST['adresa']);
        $c->setDesc($_POST['desc']);

        try {
            $c->setName($_POST['name']);
        } catch (Exception $e) {
            $errors['name'] = $e->getMessage();
        }

        

        try {
            $c->setTelefon($_POST['telefon']);
        } catch (Exception $e) {
            $errors['telefon'] = $e->getMessage();
            unset ($_POST['telefon']);
        }

        try {
            $c->setSite($_POST['site']);
        } catch (Exception $e) {
            $errors['site'] = $e->getMessage();
            unset ($_POST['site']);
        }

        try {
            $c->setLevel($_POST[level]);
        } catch (Exception $e) {
            $errors['level'] = $e->getMessage();
            $_POST['level'] = 1;
        }

        try {
            $c->setUrl($_POST['url']);
        } catch (Exception $e) {
            $errors['url'] = $e->getMessage();
            unset ($_POST['url']);
        }

        if (strlen($_POST['created']) > 0 && strtolower($_POST['created']) != 'current') {
            try {
                $c->setCreated($_POST['created']);
            } catch (Exception $e) {
                $errors['created'] = $e->getMessage();
                unset ($_POST['created']);
            }
        }
        
        
        if (strlen($_POST['updated']) > 0 && strtolower($_POST['updated']) != 'current') {
            try {
                $c->setUpdated($_POST['updated']);
            } catch (Exception $e) {
                $errors['updated'] = $e->getMessage();
                unset ($_POST['updated']);
            }
        }



        if (count($errors) > 0) $c->errors = $errors;
        return $c;

    }//_postToCompanyObj


    /**
     *
     * @return array|Application_Model_Tag
     */
    protected function _postToTags()
    {
        if (!isset($_POST['tags']) || $_POST['tags'] == '') return array();

        $tags = explode(',', $_POST['tags']);

        foreach ($tags as $tagKey => $tag) {
            $tagObj = Application_Model_TagMapper::lookupTag($tag);
            $tags[$tagKey] = $tagObj;
        }

var_dump($tags);

        return $tags;

    }//_postToTags


    /**
     *
     * @return Application_Model_Category|bool Returns category-object or false
     *
     */
    protected function _postToCategory()
    {
        if ($_POST['category'] == '0') return false;

        $category = new Application_Model_Category();
        $categoryMapper = new Application_Model_CategoryMapper();

        $res = $categoryMapper->find($_POST['category']);

        $category->setId($res[Application_Model_CategoryMapper::ID]);
        $category->setText($res[Application_Model_CategoryMapper::TEXT]);
        $category->setUrl($res[Application_Model_CategoryMapper::URL]);

        return $category;
    }

    /**************************************************************************/
    public function newAction() {
        $act = 'showform';

        $categoryMapper = new Application_Model_CategoryMapper();
        $this->view->categories = $categoryMapper->getAll();

        if (isset($_POST['act']) && $_POST['act'] == 'sent') {
            $act = 'sent';
        }

        //If form was submitted
        if ($act == 'sent'){

            $company = $this->_postToCompanyObj();

            $category = $this->_postToCategory();

            if ($category === false) {
                $company->errors['category'] = 'Category not found';
            } else {
                $company->setCategory($category);
            }

            // Process passed tags
            //$tags = $this->_postToTags();

            $act = 'ok';
            if (isset($company->errors)) {
                $act = 'errors';
                $this->view->errors = $company->errors;
            }

$this->view->company = $company;

            if ($act === 'ok') {
                $companyMapper = new Application_Model_CompanyMapper();
                $res = $companyMapper->save($company);
                
                if ($res === true) {
                    $act = 'saved';
                } else  $act = 'Failed to save: ' . $res;
            }

           
            
        }

        $this->view->act = $act;

    }//newAction()

    /**************************************************************************/
    public function deleteAction()
    {
        $params = $this->getRequest()->getParams();
        $companyMapper = new Application_Model_CompanyMapper();

        $action = ''; $confirm = 'no'; $id = false; $companyName = '';

        if (isset($params['i'])) {
            $id = $companyMapper->exists( $params['i'], $companyName );
        }

        $this->view->companyName = $companyName;
        $this->view->companyId = $id;

        if (isset($params['c'])) {
            if ($params['c'] == 'y' || $params['c'] === 'yes') {
                $confirm = 'yes';
            }
        }

        if ($id === false) {
            $this->view->act = 'CompanyNotFound';
        } else {

            if ($confirm === 'yes') {
                $countDeleted = $companyMapper->delete($id);

                if ($countDeleted > 0) {
                    $this->view->act = 'SuccessfullyDeleted';
                    $this->view->cnt = $countDeleted;
                }

            } else $this->view->act = 'PleaseConfirm';
        }

    }//deleteAction()

    public function editAction()
    {
        $act = 'nope';
        $params = $this->getRequest()->getParams();
        $companyMapper = new Application_Model_CompanyMapper();
        $categoryMapper = new Application_Model_CategoryMapper();

        $this->view->categories = $categoryMapper->getAll();

        $company = $companyMapper->find( $params['i'] );

        if ($company !== false) {
            $companyObj = $companyMapper->dbEntryToCompanyObj($company);

            $db = Zend_Registry::get('db_adaptor');
            $q = "SELECT * FROM `com_cat`, `category` WHERE "
               . "`com_cat`.`com_id` = {$companyObj->getId()} "
               . "AND `com_cat`.`cat_id` = `category`.`cat_id`";
            $res = $db->fetchRow($q);
            $categoryObj = $categoryMapper->dbEntryToCategoryObj($res);

            $companyObj->setCategory($categoryObj);

            $act = 'ok';
        } else $act = 'companyNotFound';



        if ( $act === 'ok' && $_POST['act'] === 'sent' ) {

            $c = $companyObj;
            $errors = array();

            $c->setAdresa($_POST['adresa']);
            $c->setDesc($_POST['desc']);

            try {
                $c->setName($_POST['name']);
            } catch (Exception $e) {
                $errors['name'] = $e->getMessage();
            }



            try {
                $c->setTelefon($_POST['telefon']);
            } catch (Exception $e) {
                $errors['telefon'] = $e->getMessage();
                unset ($_POST['telefon']);
            }

            try {
                $c->setSite($_POST['site']);
            } catch (Exception $e) {
                $errors['site'] = $e->getMessage();
                unset ($_POST['site']);
            }

            try {
                $c->setLevel($_POST[level]);
            } catch (Exception $e) {
                $errors['level'] = $e->getMessage();
                $_POST['level'] = 1;
            }

            try {
                $c->setUrl($_POST['url']);
            } catch (Exception $e) {
                $errors['url'] = $e->getMessage();
                unset ($_POST['url']);
            }

            if (strlen($_POST['created']) > 0 && strtolower($_POST['created']) != 'current') {
                try {
                    $c->setCreated($_POST['created']);
                } catch (Exception $e) {
                    $errors['created'] = $e->getMessage();
                    unset ($_POST['created']);
                }
            }


            if (strlen($_POST['updated']) > 0 && strtolower($_POST['updated']) != 'current') {
                try {
                    $c->setUpdated($_POST['updated']);
                } catch (Exception $e) {
                    $errors['updated'] = $e->getMessage();
                    unset ($_POST['updated']);
                }
            }

            $category = $this->_postToCategory();

            if ($category === false) {
                $errors['category'] = 'Category not found';
            } else {
                $c->setCategory($category);
            }

            if (count($errors) > 0) $act = 'errors';

        }



        //saving
        /*
        if ($act == 'ok') {
            $res = $companyMapper->save($companyObj);

            if ($res === true) {
                $act = 'saved';
            } else  $act = 'Failed to save: ' . $res;
        }
        */



        $this->view->company = $companyObj;
        $this->view->errors = $errors;
        $this->view->res = $res; //result of saving

    }//editAction()


}

?>
